# redis.py (修正后)

import logging
from typing import Annotated

from fastapi import Depends
from redis.asyncio import Redis

from app.core import settings

logger = logging.getLogger("async_redis")

_async_redis_pool: Redis | None = None


async def create_async_redis_pool() -> Redis:
    if settings.REDIS_CACHE is None:
        raise ValueError("Redis配置未设置")

    cfg = settings.REDIS_CACHE
    logger.info(f"初始化 Redis: {cfg.HOST}:{cfg.PORT}/{cfg.DB}")

    return Redis(
        host=cfg.HOST or "localhost",
        port=cfg.PORT or 6379,
        username=cfg.DBUSER,
        password=cfg.PASSWORD,
        db=cfg.DB or 0,
        decode_responses=True,
        socket_timeout=5,
        socket_connect_timeout=5,
        max_connections=20,
        health_check_interval=30,
        retry_on_timeout=True,
    )


async def init_async_redis_pool() -> None:
    global _async_redis_pool
    if _async_redis_pool is None:
        _async_redis_pool = await create_async_redis_pool()
        logger.info("Redis 连接池初始化成功")


async def close_async_redis_pool() -> None:
    global _async_redis_pool
    if _async_redis_pool:
        await _async_redis_pool.close()
        _async_redis_pool = None
        logger.info("Redis 连接池已关闭")


async def get_async_redis() -> Redis:
    if _async_redis_pool is None:
        raise RuntimeError("Redis 连接池未初始化")
    return _async_redis_pool


# FastAPI 依赖注入
async def get_redis() -> Redis:
    return await get_async_redis()


RedisDep = Annotated[Redis, Depends(get_redis)]
